
import numpy as np
import matplotlib.pyplot as plt
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# 准备数据
X = np.array([[1, 2], [2, 3], [3, 4], [4, 6], [5, 7], [6, 8]])
y = np.array([0, 0, 0, 1, 1, 1])

# 应用 LDA
lda = LinearDiscriminantAnalysis(n_components=1)
X_lda = lda.fit_transform(X, y)

# 获取 LDA 的投影方向
w = lda.coef_[0]  # LDA 的权重向量
w /= np.linalg.norm(w)  # 归一化

# 计算每个点到 LDA 投影的投影点
# 计算每个点的投影
projections = X.dot(w)
projections = np.vstack((projections, projections)).T * w

# 可视化原始数据、投影方向和投影点
# 设置图形尺寸
plt.figure(figsize=(10, 6))

# 绘制原始数据
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis', marker='o', label='Original Data')

# 绘制投影方向
plt.plot([0, w[0]*10], [0, w[1]*10], color='red', linewidth=2, label='LDA Projection Direction')

# 绘制每个点到投影方向的投影线
for i in range(len(X)):
    plt.plot([X[i, 0], projections[i, 0]], [X[i, 1], projections[i, 1]], 'k--', linewidth=1)

# 绘制投影点
plt.scatter(projections[:, 0], projections[:, 1], c=y, cmap='viridis', marker='x', s=100, label='Projection Points')

# 设置图例和标题
plt.title('LDA Projection')
plt.xlabel('x1')
plt.ylabel('x2')
plt.legend()

# 显示图形
plt.show()